package Aleehot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: c06
 * Package: Aleehot100
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/5/21 16:35
 * @Version 1.0
 * @Since 1.0
 */
public class c06 {
    public static void main(String[] args) {
        int[] arr = {-1,0,1,2,-1,-4};
        System.out.println(threeSum(arr));
    }

    static List<List<Integer>> res = new ArrayList<>();
    public static List<List<Integer>> threeSum(int[] nums) {
        res.clear();
        int first, second, third, target = 0;

        // 排序
        Arrays.sort(nums);
        for (first = 0; first <= nums.length - 3; first++) {
            target = 0;
            // 重复判断
            if(first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            target += nums[first];
            third = nums.length - 1;
            // 第二个元素
            for (second = first + 1; second <= nums.length - 2; second++) {
                if(second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                // 双指针
                while(second < third && nums[second] + nums[third] > -target) {
                    third --;
                }
                // 统计结果
                if(third != second && nums[second] + nums[third] == -target) {
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    res.add(list);
                }
            }
        }
        return res;
    }

}
